//
// Created by yunnan xu on 2020/11/14.
//

#include <ext.hpp>
#include <chrono>
#include <ctime>
#include "Pass.h"
#include "EngineCore.h"
#include "RenderItem.h"
#include "GLESUtils.h"
#include "Scene.h"
#include "Camera.h"


GLESPass::GLESPass() : Pass(), vertexShader(0), fragmentShader(0)
{
    program = glCreateProgram();
    if (program == 0)
    {
        LOGE("GLESPass Create Program 000000");
        TryGetGLError("GLESPass Create Program");
    }
}


void GLESPass::InitShaders(std::unordered_map<ShaderType, std::string> shader_dict)
{
    if (shader_dict.find(ShaderType::FragmentShader) != shader_dict.end())
    {
        auto fragment_shader_path = shader_dict[ShaderType::FragmentShader];
        fragmentShader = GLESShaderMgr::GetInstance()->GetShaderByPath(fragment_shader_path);
        GL_CHECK(glAttachShader(program, fragmentShader));
    }

    if (shader_dict.find(ShaderType::VertexShader) != shader_dict.end())
    {
        auto vertex_shader_path = shader_dict[ShaderType::VertexShader];
        vertexShader = GLESShaderMgr::GetInstance()->GetShaderByPath(vertex_shader_path);
        GL_CHECK(glAttachShader(program, vertexShader));
    }

    if (shader_dict.find(ShaderType::ComputeShader) != shader_dict.end())
    {
        auto compute_shader_path = shader_dict[ShaderType::ComputeShader];
        computeShader = GLESShaderMgr::GetInstance()->GetShaderByPath(compute_shader_path);
        GL_CHECK(glAttachShader(program, computeShader));
    }

    GL_CHECK(glLinkProgram(program));

    GLint link_res;

    GL_CHECK(glGetProgramiv(program, GL_LINK_STATUS, &link_res));

    if (link_res == GL_FALSE)
    {
        LOGE("glGetProgramiv error ... ");
    }
    else
    {
        LOGI("glGetProgramiv success ... ");
        InitShaderUniformLocation();
    }
}